package mdb.com.vn.web.beans;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import mdb.com.vn.model.Customer;
import mdb.com.vn.model.IBankingSms;
import mdb.com.vn.services.MDBServices;
import mdb.com.vn.utils.DateUtils;
import mdb.com.vn.utils.TextUtil;
import mdb.com.vn.web.view.IbSmsDataModel;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

@ManagedBean(name = "iBSmsBean")
@ViewScoped
public class IBSmsBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Date processDate;
	private StreamedContent file;
	private List<IBankingSms> listOfIbSms;
	private List<Object> listOfobjects;

	private boolean btnVisible;
	private boolean btnSaveVisible;
	
	private IbSmsDataModel ibSmsDataModel;
	private IBankingSms iBankingSmsSelected;
	
	private Date lastUpdated;
	private Date nextProcess;

	@ManagedProperty("#{mdbServices}")
	private MDBServices mdbServices;
	
	@PostConstruct
	public void init(){
		listOfIbSms = new ArrayList<IBankingSms>();
		listOfIbSms = mdbServices.getIBSmsByProperties(TextUtil.PROCESSED);
		ibSmsDataModel = new IbSmsDataModel(listOfIbSms);
		lastUpdated = mdbServices.getLastUpdatedLoans(TextUtil.IB_MODULE);
		nextProcess = DateUtils.nextMonth(lastUpdated, 1);
	}
	public void searchLoansByDate() {
		if (processDate != null) {
			listOfIbSms = mdbServices.getIBSmsByIBSMSDateStatus(TextUtil.PROCESSED, processDate);
			ibSmsDataModel = new IbSmsDataModel(listOfIbSms);
		} else {
			listOfIbSms = mdbServices.getIBSmsByProperties(TextUtil.PROCESSED);
			ibSmsDataModel = new IbSmsDataModel(listOfIbSms);
		}
	}
	
	public void createExcelIBByPoi(){
		Row row = null;
		Cell cell = null;
		try {
			Workbook wb = new HSSFWorkbook();
			HSSFCellStyle styleHeader = (HSSFCellStyle) wb.createCellStyle();
			HSSFFont fontHeader = (HSSFFont) wb.createFont();
			fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			styleHeader.setFont(fontHeader);
			Sheet sheet = wb.createSheet("IBanking");
			row = sheet.createRow((short) 0);
			List<String> columnNames = new ArrayList<String>();

			columnNames.add("Số gcif");
			columnNames.add("Tên khách hàng");
			columnNames.add("Số điện thoại");
			columnNames.add("Ngày bắt đầu");
			columnNames.add("Ngày kết thúc");
			columnNames.add("Số tiền chuyển khoản IB");
			columnNames.add("Số lần giao dịch");
			columnNames.add("Tổng số mã dự thưởng");
			columnNames.add("Mã dự thưởng");
			columnNames.add("Điểm giao dịch");
			for (int i = 0; i < columnNames.size(); i++) {
				cell = row.createCell(i);
				cell.setCellValue(columnNames.get(i));
				cell.setCellStyle(styleHeader);
			}
			int j = 1;
			List<Object[]> tabularData = new ArrayList<Object[]>();
			for (IBankingSms iBankingSms : listOfIbSms) {
				
				Customer customer = mdbServices.getCustomerInfos(
						iBankingSms.getCustomerId());
				String customerName = "";
				String companyName = "";
				if (customer != null){
					customerName = customer.getCustomerName();
					companyName = mdbServices.getCompanyNameByCode(customer.getBranchCode());
				}else{
					customerName = "N/A";
					companyName = "N/A";
				}
				Calendar cal = Calendar.getInstance();
		        cal.setTime(iBankingSms.getProcessDate());
		        int month = cal.get(Calendar.MONTH);
		        int year = cal.get(Calendar.YEAR);
		        String dateFrom = "";
		        if(month == 11 && year == 2013){
		        	dateFrom = "09/12/2013"; 
		        }
		        if(month == 0 && year == 2014){
		        	dateFrom = "09/12/2013"; 
		        }
		        if(month == 1 && year == 2014){
		        	dateFrom = "10/01/2014";
		        }
		        if(month == 2 && year ==2014){
		        	dateFrom = "10/02/2014";
		        }
		        
				String lkd_num_g2 = mdbServices.getAllLuckyDrawG2Code(TextUtil.IB_MODULE,iBankingSms.getCustomerId(),iBankingSms.getProcessDate(), TextUtil.PROCESSED);
				tabularData
						.add(new Object[] {
								iBankingSms.getCustomerId(),
								customerName,
								iBankingSms.getPhoneNum(),
								dateFrom,
								DateUtils.format(iBankingSms.getProcessDate(), "dd/MM/yyyy") ,
								iBankingSms.getTotalAmtTxn(),
								iBankingSms.getTotalCounterTxn(),
								iBankingSms.getLkdNum(),
								lkd_num_g2,
								companyName});
			}
			
			HSSFCellStyle styleRow = (HSSFCellStyle) wb
					.createCellStyle();
			HSSFFont fontRow = (HSSFFont) wb.createFont();
			fontRow.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
			styleRow.setFont(fontRow);
			
			for (Object[] temp : tabularData) {
				row = sheet.createRow((short) j);
				for (int k = 0; k < temp.length; k++) {
					cell = row.createCell(k);
					cell.setCellValue(temp[k].toString());
					cell.setCellStyle(styleRow);
				}
				j++;
			}
			tabularData = null;
			String excelFileName = "IB_REPORT_SMS.xls";
			FileOutputStream fos = new FileOutputStream(excelFileName);
			wb.write(fos);
			fos.flush();
			fos.close();
			InputStream stream = new BufferedInputStream(new FileInputStream(
					excelFileName));
			file = new DefaultStreamedContent(stream, "application/xls",
					excelFileName);
			setBtnVisible(true);
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_INFO,
									"Xử lý xuất dữ liệu thành công",
									"Vui lòng nhấn nút 'Tải về máy' để tại file excell về máy."));
		} catch (Exception e) {
			setBtnVisible(false);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Xử lý xuất dữ liệu thất bại",
							"Vui lòng liên hệ quản trị hệ thống."));
			e.printStackTrace();
		}

	
}

	public void downloadPreventedLoans() {
		file = null;
	}
	/**
	 * @return the processDate
	 */
	public Date getProcessDate() {
		return processDate;
	}
	/**
	 * @param processDate the processDate to set
	 */
	public void setProcessDate(Date processDate) {
		this.processDate = processDate;
	}
	/**
	 * @return the listOfIbSms
	 */
	public List<IBankingSms> getListOfIbSms() {
		return listOfIbSms;
	}
	/**
	 * @param listOfIbSms the listOfIbSms to set
	 */
	public void setListOfIbSms(List<IBankingSms> listOfIbSms) {
		this.listOfIbSms = listOfIbSms;
	}
	/**
	 * @return the listOfobjects
	 */
	public List<Object> getListOfobjects() {
		return listOfobjects;
	}
	/**
	 * @param listOfobjects the listOfobjects to set
	 */
	public void setListOfobjects(List<Object> listOfobjects) {
		this.listOfobjects = listOfobjects;
	}
	/**
	 * @return the btnVisible
	 */
	public boolean isBtnVisible() {
		return btnVisible;
	}
	/**
	 * @param btnVisible the btnVisible to set
	 */
	public void setBtnVisible(boolean btnVisible) {
		this.btnVisible = btnVisible;
	}
	/**
	 * @return the btnSaveVisible
	 */
	public boolean isBtnSaveVisible() {
		return btnSaveVisible;
	}
	/**
	 * @param btnSaveVisible the btnSaveVisible to set
	 */
	public void setBtnSaveVisible(boolean btnSaveVisible) {
		this.btnSaveVisible = btnSaveVisible;
	}
	
	/**
	 * @return the iBankingSmsSelected
	 */
	public IBankingSms getiBankingSmsSelected() {
		return iBankingSmsSelected;
	}
	/**
	 * @param iBankingSmsSelected the iBankingSmsSelected to set
	 */
	public void setiBankingSmsSelected(IBankingSms iBankingSmsSelected) {
		this.iBankingSmsSelected = iBankingSmsSelected;
	}
	/**
	 * @return the lastUpdated
	 */
	public Date getLastUpdated() {
		return lastUpdated;
	}
	/**
	 * @param lastUpdated the lastUpdated to set
	 */
	public void setLastUpdated(Date lastUpdated) {
		this.lastUpdated = lastUpdated;
	}
	/**
	 * @return the nextProcess
	 */
	public Date getNextProcess() {
		return nextProcess;
	}
	/**
	 * @param nextProcess the nextProcess to set
	 */
	public void setNextProcess(Date nextProcess) {
		this.nextProcess = nextProcess;
	}
	/**
	 * @return the file
	 */
	public StreamedContent getFile() {
		return file;
	}
	/**
	 * @return the ibSmsDataModel
	 */
	public IbSmsDataModel getIbSmsDataModel() {
		return ibSmsDataModel;
	}
	/**
	 * @param mdbServices the mdbServices to set
	 */
	public void setMdbServices(MDBServices mdbServices) {
		this.mdbServices = mdbServices;
	}
	
	
}
